package com.hm.base.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hm.base.auto.su.BeanUtil;
import com.hm.base.domain.Menu;
import com.hm.base.mapper.MenuMapper;
import com.hm.base.vo.MenuVo;
import com.hm.common.exception.ErrorCode;
import com.hm.common.exception.ServiceException;
import com.hm.common.su.bean.PageInfo;
import com.hm.common.su.bean.PageInfo.PageParam;
import com.hm.common.util.CommonUtil;
import com.hm.common.util.DateUtil;
import com.hm.common.util.StringUtil;

/**
 * @author shishun.wang
 * @date 下午9:49:09 2017年8月17日
 * @version 1.0
 * @describe
 */
@Service
public class MenuServiceImpl implements MenuService {

	@Autowired
	private MenuMapper menuMapper;

	@Override
	public PageInfo<MenuVo> query(PageParam pageParam, Long parentId, String name) {
		Page<Menu> page = PageHelper.startPage(pageParam.getPage(), pageParam.getSize(), true);

		Menu menu = new Menu();
		if (StringUtil.isNotBlank(name)) {
			menu.setName(name);
		}
		if (CommonUtil.isNotEmpty(parentId)) {
			menu.setParentId(parentId);
		}

		menuMapper.query(menu);
		List<MenuVo> vos = new ArrayList<MenuVo>();
		page.getResult().forEach(item -> {
			MenuVo vo = new MenuVo();
			BeanUtil.copyProperties(item, vo);
			vo.setCreateTime(DateUtil.data2long(item.getCreateTime()));
			if (CommonUtil.isNotEmpty(vo.getParentId())) {
				Menu parentMenu = menuMapper.selectByPrimaryKey(vo.getParentId());
				if (CommonUtil.isNotEmpty(parentMenu)) {
					vo.setParentName(parentMenu.getName());
				}
			}

			vos.add(vo);
		});

		return new PageInfo<MenuVo>(vos, page.getPages(), page.getTotal());
	}

	@Override
	public MenuVo getMenu(Long menuId) {
		if (CommonUtil.isEmpty(menuId)) {
			throw ServiceException.warning(ErrorCode.REQUIRED_PARAMETERS_MISSING);
		}
		Menu menu = menuMapper.selectByPrimaryKey(menuId);
		if (CommonUtil.isEmpty(menu)) {
			throw ServiceException.warning(ErrorCode.DATA_NOT_FOUND);
		}

		MenuVo vo = new MenuVo();
		BeanUtil.copyProperties(menu, vo);
		if (CommonUtil.isNotEmpty(vo.getParentId())) {
			Menu parentMenu = menuMapper.selectByPrimaryKey(vo.getParentId());
			if (CommonUtil.isNotEmpty(parentMenu)) {
				vo.setParentName(parentMenu.getName());
			}
		}

		return vo;
	}
}
